@if(!isset($__csrf_meta_added))
<meta name="csrf-token" content="{{ csrf_token() }}">
@php $__csrf_meta_added = true; @endphp
@endif

<div class="row">
    <div class="col-md-3">
        <!-- 左侧平台清单 -->
        <div class="card">
            <div class="card-header bg-light">
                <h6 class="mb-0"><i class="fa fa-list"></i> 机构清单</h6>
            </div>
            <div class="card-body p-0">
                <div class="list-group list-group-flush">
                    @foreach($merchants as $merchant)
                    <a href="#" class="list-group-item list-group-item-action {{ $merchant['active'] ? 'active' : '' }}" 
                       data-platform-id="{{ $merchant['id'] }}" 
                       data-platform-name="{{ $merchant['name'] }}">
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="d-flex align-items-center">
                                <i class="fa fa-map-marker text-{{ $merchant['color'] }} mr-2"></i>
                                <span>{{ $merchant['name'] }}</span>
                            </div>
                            <span class="badge badge-{{ $merchant['active'] ? 'primary' : 'secondary' }}">
                                （{{ $merchant['assigned_count'] ?? 0 }}｜{{ $merchant['vendor_count'] }}）
                            </span>
                        </div>
                    </a>
                    @endforeach
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-9">
        <!-- 右侧供应商列表 -->
        <div class="card">
            <div class="card-header bg-light">
                <div class="d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">
                        <i class="fa fa-store"></i> 供应商清单
                    </h6>
                    <small class="text-muted">
                        已选门店：{{ $selectedStoreData['name'] }}
                    </small>
                </div>
            </div>
            <div class="card-body">
                <!-- 搜索框和批量操作按钮 -->
                <div class="row mb-3">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="supplier_name" class="form-label">供应商名称：</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="supplier_name" placeholder="请输入供应商名称">
                                <div class="input-group-append">
                                    <span class="input-group-text"><i class="fa fa-search"></i></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex justify-content-end align-items-end h-100">
                            <div class="btn-group btn-group-sm" id="batchActions">
                                <button type="button" class="btn btn-primary" onclick="batchAssign()" disabled>
                                    <i class="fa fa-save"></i> 保存分配
                                </button>
                                <button type="button" class="btn btn-secondary" onclick="clearSelection()" disabled>
                                    <i class="fa fa-undo"></i> 清除选择
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 供应商表格 -->
                <div class="table-responsive">
                    <table class="table table-hover table-striped mb-0">
                        <thead class="bg-light">
                            <tr>
                                <th style="width: 50px;">
                                    <div class="custom-control custom-checkbox">
                                        <input type="checkbox" class="custom-control-input" id="selectAll">
                                        <label class="custom-control-label" for="selectAll"></label>
                                    </div>
                                </th>
                                <th style="width: 80px;">供应商ID</th>
                                <th style="width: 150px;">供应商名称</th>
                                <th style="width: 200px;">供应商</th>
                                <th style="width: 150px;">申请人手机号</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($suppliers as $supplier)
                            <tr class="{{ $supplier['assigned'] ? 'table-success' : '' }}">
                                <td>
                                    <div class="custom-control custom-checkbox">
                                        <input type="checkbox" class="custom-control-input supplier-checkbox" 
                                               id="supplier_{{ $supplier['id'] }}" 
                                               value="{{ $supplier['id'] }}"
                                               {{ $supplier['assigned'] ? 'checked' : '' }}>
                                        <label class="custom-control-label" for="supplier_{{ $supplier['id'] }}"></label>
                                    </div>
                                </td>
                                <td><strong>{{ $supplier['id'] }}</strong></td>
                                <td>
                                    {{ $supplier['name'] }}
                                    @if($supplier['assigned'])
                                        <span class="badge badge-success ml-2">已分配</span>
                                    @endif
                                </td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="avatar avatar-sm rounded-circle mr-2">
                                            <img src="{{ $supplier['supplier']['avatar'] }}" alt="{{ $supplier['supplier']['name'] }}" class="rounded-circle" style="width: 40px; height: 40px;">
                                        </div>
                                        <div>
                                            <div><strong>{{ $supplier['supplier']['name'] }}</strong></div>
                                            <small class="text-muted">ID: {{ $supplier['supplier']['id'] }}</small>
                                        </div>
                                    </div>
                                </td>
                                <td>{{ $supplier['phone'] }}</td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>

                <!-- 底部统计 -->
                <div class="d-flex justify-content-between align-items-center mt-3 pt-3 border-top">
                    <div class="text-muted">
                        共 {{ count($suppliers) }} 条记录（无分页，显示所有数据）
                    </div>
                    <div class="text-muted">
                        <i class="fa fa-list"></i> 全量显示
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 供应商详情弹窗 -->
<div class="modal fade" id="supplierDetailModal" tabindex="-1" role="dialog" aria-labelledby="supplierDetailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="supplierDetailModalLabel">
                    <i class="fa fa-user-tie"></i> 供应商详情
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="supplierDetailContent">
                <div class="text-center py-5">
                    <i class="fa fa-spinner fa-spin fa-2x text-muted"></i>
                    <p class="text-muted mt-2">加载中...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.avatar {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
}

.form-label {
    font-weight: 500;
    margin-bottom: 5px;
    color: #495057;
}

.table th {
    border-top: none;
    font-weight: 600;
    color: #495057;
    background-color: #f8f9fa !important;
}

.table td {
    vertical-align: middle;
    padding: 12px 8px;
}

.list-group-item.active {
    background-color: #007bff;
    border-color: #007bff;
}

.list-group-item:hover {
    background-color: #f8f9fa;
}

.list-group-item.active:hover {
    background-color: #0056b3;
}

.card-header h6 {
    font-weight: 600;
}

.btn-group-sm > .btn, .btn-sm {
    padding: 0.25rem 0.5rem;
    font-size: 0.875rem;
    line-height: 1.5;
    border-radius: 0.2rem;
}

.custom-control-input:indeterminate ~ .custom-control-label::before {
    background-color: #007bff;
    border-color: #007bff;
}

.custom-control-input:indeterminate ~ .custom-control-label::after {
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='4' height='4' viewBox='0 0 4 4'%3e%3cpath stroke='%23fff' d='M0,2 L4,2'/%3e%3c/svg%3e");
}

.custom-checkbox .custom-control-label::before {
    border-radius: 0.25rem;
}

.table .custom-control {
    margin-bottom: 0;
}

/* 批量操作按钮样式 */
#batchActions .btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

#batchActions .btn:not(:disabled):hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
</style>

<script>
function selectPlatform(merchant_id, name) {
    // 移除所有active类
    $('.list-group-item').removeClass('active');
    
    // 添加active类到当前选中项
    event.target.closest('.list-group-item').classList.add('active');
    
    // 显示加载状态
    showLoadingState();
    
    // 发送Ajax请求获取对应平台的供应商数据
    loadSuppliersByPlatform(merchant_id);
}

// 加载指定平台的供应商列表
function loadSuppliersByPlatform(merchant_id) {
    $.ajax({
        url: '{{ route("dcat.admin.admin.api.suppliers.by-merchant") }}',
        type: 'GET',
        data: {
            merchant_id: merchant_id,
            supplier_name: $('#supplier_name').val(),
            store_id: '{{ $selectedStoreData["id"] ?? 1 }}'
        },
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                updateSupplierTable(response.data);
                hideLoadingState();
            } else {
                showMessage('获取供应商列表失败：' + response.message, 'error');
                hideLoadingState();
            }
        },
        error: function(xhr, status, error) {
            console.error('获取供应商列表失败:', error);
            showMessage('获取供应商列表失败，请重试', 'error');
            hideLoadingState();
        }
    });
}

// 更新供应商表格
function updateSupplierTable(suppliers) {
    var tbody = $('table tbody');
    tbody.empty();
    
    if (suppliers.length === 0) {
        tbody.append(`
            <tr>
                <td colspan="5" class="text-center text-muted py-4">
                    <i class="fa fa-inbox fa-2x mb-2"></i>
                    <p>暂无供应商数据</p>
                </td>
            </tr>
        `);
        return;
    }
    
    suppliers.forEach(function(supplier) {
        var assignedClass = supplier.assigned ? 'table-success' : '';
        var checkedAttr = supplier.assigned ? 'checked' : '';
        var assignedBadge = supplier.assigned ? '<span class="badge badge-success ml-2">已分配</span>' : '';
        
        var row = `
            <tr class="${assignedClass}">
                <td>
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input supplier-checkbox" 
                               id="supplier_${supplier.id}" 
                               value="${supplier.id}"
                               ${checkedAttr}>
                        <label class="custom-control-label" for="supplier_${supplier.id}"></label>
                    </div>
                </td>
                <td><strong>${supplier.id}</strong></td>
                <td>
                    ${supplier.name}
                    ${assignedBadge}
                </td>
                <td>
                    <div class="d-flex align-items-center">
                        <div class="avatar avatar-sm rounded-circle mr-2">
                            <img src="${supplier.supplier.avatar}" alt="${supplier.supplier.name}" class="rounded-circle" style="width: 40px; height: 40px;">
                        </div>
                        <div>
                            <div><strong>${supplier.supplier.name}</strong></div>
                            <small class="text-muted">ID: ${supplier.supplier.id}</small>
                        </div>
                    </div>
                </td>
                <td>${supplier.phone}</td>
            </tr>
        `;
        tbody.append(row);
    });
    
    // 重新绑定事件
    $(document).off('change', '.supplier-checkbox').on('change', '.supplier-checkbox', updateBatchActions);
    
    // 更新批量操作状态
    updateBatchActions();
}

// 显示加载状态
function showLoadingState() {
    var tbody = $('table tbody');
    tbody.html(`
        <tr>
            <td colspan="5" class="text-center py-4">
                <i class="fa fa-spinner fa-spin fa-2x text-muted"></i>
                <p class="text-muted mt-2">加载中...</p>
            </td>
        </tr>
    `);
}

// 隐藏加载状态
function hideLoadingState() {
    // 加载完成后会通过updateSupplierTable更新内容
}

// 显示消息提示
function showMessage(message, type = 'info') {
    if (typeof Dcat !== 'undefined') {
        if (type === 'success') {
            Dcat.success(message);
        } else if (type === 'error') {
            Dcat.error(message);
        } else {
            Dcat.info(message);
        }
    } else {
        // 备用方案：使用SweetAlert2
        if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: type === 'success' ? '成功' : type === 'error' ? '错误' : '提示',
                text: message,
                icon: type,
                confirmButtonText: '确定'
            });
        } else {
            alert(message);
        }
    }
}

// 全选/取消全选功能
function toggleSelectAll() {
    var selectAllCheckbox = $('#selectAll');
    var supplierCheckboxes = $('.supplier-checkbox');
    
    supplierCheckboxes.prop('checked', selectAllCheckbox.prop('checked'));
    updateBatchActions();
}

// 更新批量操作区域显示
function updateBatchActions() {
    var checkedBoxes = $('.supplier-checkbox:checked');
    var count = checkedBoxes.length;
    var totalBoxes = $('.supplier-checkbox').length;
    
    // 更新按钮状态（保存分配按钮始终可用，清除选择按钮在有选择时才可用）
    var batchButtons = $('#batchActions button');
    var saveButton = batchButtons.filter(':first'); // 保存分配按钮
    var clearButton = batchButtons.filter(':last');  // 清除选择按钮
    
    // 保存分配按钮始终可用
    saveButton.prop('disabled', false);
    saveButton.removeClass('disabled');
    
    // 清除选择按钮只有在有选择时才可用
    if (count > 0) {
        clearButton.prop('disabled', false);
        clearButton.removeClass('disabled');
    } else {
        clearButton.prop('disabled', true);
        clearButton.addClass('disabled');
    }
    
    // 更新全选按钮状态
    var selectAllCheckbox = $('#selectAll');
    
    if (count === 0) {
        selectAllCheckbox.prop('indeterminate', false);
        selectAllCheckbox.prop('checked', false);
    } else if (count === totalBoxes) {
        selectAllCheckbox.prop('indeterminate', false);
        selectAllCheckbox.prop('checked', true);
    } else {
        selectAllCheckbox.prop('indeterminate', true);
    }
}

// 批量分配
function batchAssign() {
    var selectedIds = [];
    $('.supplier-checkbox:checked').each(function() {
        selectedIds.push($(this).val());
    });
    
    // 获取当前选中的平台ID
    var activePlatformId = $('.list-group-item.active').data('platform-id');
    var activePlatformName = $('.list-group-item.active').data('platform-name');
    
    if (!activePlatformId) {
        showMessage('请先选择一个机构', 'error');
        return;
    }
    
    // 获取当前选中供应商的数量和总数
    var totalSuppliers = $('.supplier-checkbox').length;
    var selectedCount = selectedIds.length;
    var unselectedCount = totalSuppliers - selectedCount;
    
    // 构建确认消息
    var confirmMessage = `确定要保存当前分配吗？\n\n`;
    confirmMessage += `• 平台：${activePlatformName}\n`;
    confirmMessage += `• 将分配 ${selectedCount} 个供应商给当前门店\n`;
    if (unselectedCount > 0) {
        confirmMessage += `• 将取消分配 ${unselectedCount} 个供应商\n`;
    }
    confirmMessage += `\n此操作将仅更新当前平台的供应商分配。`;
    
    // 使用Dcat Admin的确认框
    if (typeof Dcat !== 'undefined' && Dcat.confirm) {
        Dcat.confirm('保存分配确认', confirmMessage, function() {
            // 发送Ajax请求进行批量分配
            $.ajax({
                url: '{{ route("dcat.admin.admin.api.suppliers.batch-assign") }}',
                type: 'POST',
                data: {
                    vendor_ids: selectedIds,
                    store_id: '{{ $selectedStoreData["id"] ?? 1 }}',
                    merchant_id: activePlatformId,
                    _token: $('meta[name="csrf-token"]').attr('content')
                },
                dataType: 'json',
                success: function(response) {
                    if (response.status === 'success') {
                        showMessage(response.message, 'success');
                        clearSelection();
                        // 刷新当前平台的供应商列表和统计数据
                        var activePlatformId = $('.list-group-item.active').data('platform-id');
                        if (activePlatformId) {
                            loadSuppliersByPlatform(activePlatformId);
                            // 刷新页面以更新左侧平台统计数据
                            setTimeout(function() {
                                location.reload();
                            }, 1000);
                        }
                    } else {
                        showMessage('批量分配失败：' + response.message, 'error');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('批量分配失败:', error);
                    showMessage('批量分配失败，请重试', 'error');
                }
            });
        });
    } else {
        // 备用方案：使用SweetAlert2
        Swal.fire({
            title: '保存分配确认',
            html: `确定要保存当前分配吗？<br><br>
                   • 平台：${activePlatformName}<br>
                   • 将分配 ${selectedCount} 个供应商给当前门店<br>
                   ${unselectedCount > 0 ? `• 将取消分配 ${unselectedCount} 个供应商<br>` : ''}
                   <br>此操作将仅更新当前平台的供应商分配。`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: '确定保存',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                // 发送Ajax请求进行批量分配
                $.ajax({
                    url: '{{ route("dcat.admin.admin.api.suppliers.batch-assign") }}',
                    type: 'POST',
                    data: {
                        vendor_ids: selectedIds,
                        store_id: '{{ $selectedStoreData["id"] ?? 1 }}',
                        platform_id: activePlatformId,
                        _token: $('meta[name="csrf-token"]').attr('content')
                    },
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            showMessage(response.message, 'success');
                            clearSelection();
                            // 刷新当前平台的供应商列表和统计数据
                            var activePlatformId = $('.list-group-item.active').data('platform-id');
                            if (activePlatformId) {
                                loadSuppliersByPlatform(activePlatformId);
                                // 刷新页面以更新左侧平台统计数据
                                setTimeout(function() {
                                    location.reload();
                                }, 1000);
                            }
                        } else {
                            showMessage('批量分配失败：' + response.message, 'error');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('批量分配失败:', error);
                        showMessage('批量分配失败，请重试', 'error');
                    }
                });
            }
        });
    }
}



// 清除选择
function clearSelection() {
    $('.supplier-checkbox').prop('checked', false);
    $('#selectAll').prop('checked', false);
    updateBatchActions();
}

// 页面加载完成后初始化
$(document).ready(function() {
    // 初始化工具提示
    $('[data-toggle="tooltip"]').tooltip();
    
    // 全选按钮事件
    $('#selectAll').on('change', toggleSelectAll);
    
    // 单个选择框事件
    $(document).on('change', '.supplier-checkbox', updateBatchActions);
    
    // 平台选择事件
    $('.list-group-item').on('click', function(e) {
        e.preventDefault();
        var platformId = $(this).data('platform-id');
        var platformName = $(this).data('platform-name');
        selectPlatform(platformId, platformName);
    });
    
    // 搜索功能 - 使用防抖避免频繁请求
    var searchTimeout;
    $('#supplier_name').on('input', function() {
        clearTimeout(searchTimeout);
        var searchTerm = $(this).val();
        
        searchTimeout = setTimeout(function() {
            // 获取当前选中的平台ID
            var activePlatformId = $('.list-group-item.active').data('platform-id');
            if (activePlatformId) {
                loadSuppliersByPlatform(activePlatformId);
            }
        }, 500); // 500ms防抖延迟
    });
});
</script>